package talk_server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Talker {
	private BufferedReader br;
	private BufferedWriter bw;
	private InputStream in;
	private OutputStream out;
	private Socket socket;
	private boolean isAlive = true;
	
	public Talker(String ip, int port) throws UnknownHostException, IOException
	{
		this.socket=new Socket(ip,port);
		init();
	}
	
	public Talker(Socket socket)
	{
		this.socket=socket;
		try {
			init();
		} catch (IOException e) {
			System.out.println("TALKER: ERRORE I/O");
			isAlive=false;
		}
	}
	
	private void init() throws IOException
	{
			in = socket.getInputStream();
			out = socket.getOutputStream();
			
			br = new BufferedReader(new InputStreamReader(in));
			bw = new BufferedWriter(new OutputStreamWriter(out));
	}
	
	public BufferedWriter getWriter()
	{
		return bw;
	}
	
	public BufferedReader getReader()
	{
		return br;
	}
	
	public void write(String msg) throws IOException
	{
		if(!isAlive) return;
		bw.write(msg + "\n");
		bw.flush();
	}
	
	public String read() throws IOException
	{
		if(!isAlive) return "#ERROR#";
		return br.readLine();
	}
	
	public void close() throws IOException
	{
		br.close();
		bw.close();
		in.close();
		out.close();
		socket.close();	
	}
	
	public void setTimeOut(int millisecs)
	{
		if(!isAlive) return;
		if(millisecs!=0)
			System.out.println("TIMEOUT: " + millisecs + " ms");
		else
			System.out.println("NO TIMEOUT");
		try {
			this.socket.setSoTimeout(millisecs);
		} catch (SocketException e) {
			System.out.println("TALKER: ERRORE DURANTEIL TIMEOUT");
		}
	}
	
	public boolean isRunning()
	{
		return isAlive;
	}
}
